//
//  AZURLRequest.m
//  AZNetwork
//
//  Created by GorXion on 2018/4/2.
//  Copyright © 2018年 gaoX. All rights reserved.
//

#import "AZURLRequest.h"
#import "AZURLCache.h"
#import "AFHTTPSessionManager+AZURLRequest.h"

@interface AZURLRequest ()

@property (nonatomic, strong) NSURL *baseURL;
@property (nonatomic, copy) NSString *path;

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation AZURLRequest

- (instancetype)initWithBaseURL:(NSURL *)baseURL
                           path:(NSString *)path
                     parameters:(NSDictionary *)parameters
{
    self = [super init];
    if (self) {
        _baseURL = baseURL;
        _path = path;
        _parameters = parameters;
    }
    return self;
}

#pragma mark - public
+ (instancetype)requestWithBaseURL:(NSURL *)baseURL
                              path:(NSString *)path
                        parameters:(NSDictionary *)parameters
{
    return [[self alloc] initWithBaseURL:baseURL path:path parameters:parameters];
}

- (void)startWithSuccess:(void (^)(id))success
                 failure:(void (^)(NSError *))failure
{
    [self startWithCache:nil success:success failure:failure];
}

- (void)startWithCache:(void (^)(id))cache
               success:(void (^)(id))success
               failure:(void (^)(NSError *))failure
{
    if (cache) {
        id data = [[AZURLCache sharedURLCache] cachedDataForRequest:self];
        !data ?: cache(data);
    }
    
    [self.manager startRequest:self success:^(id response) {
        !success ?: success(response);
        if (cache) [[AZURLCache sharedURLCache] storeCachedData:response forRequest:self];
    } failure:failure];
}

#pragma mark - getter
- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (NSString *)URLString
{
    if (!self.path) return self.baseURL.absoluteString;
    return [NSURL URLWithString:self.path relativeToURL:self.baseURL].absoluteString;
}

- (AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer
{
    return self.manager.requestSerializer;
}

- (AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer
{
    return self.manager.responseSerializer;
}

@end
